<script setup lang="ts">
	import { ref } from 'vue'
	import { onLoad } from '@dcloudio/uni-app'
	import { matchSignType } from '@/utils/types'
	import information from '@/components/informationPerson/index.vue'
	import { formValidate, msg, phoneCode, wechatPayment } from '@/utils/tools'
	import {

		getEventsItemTree,
		personalRegistry,
		personOrderInfo,
		creatOrder,
		getOrderPrice
	} from '@/api/match'
	import { signup } from '@/api/team'
	import { useStore } from "vuex";

	const store = useStore()

	const bottomPadding = (uni.getSystemInfoSync().screenHeight as number) - (uni.getSystemInfoSync().safeArea.bottom as number)
	const agreeToExplain = ref(false)
	const agreeToInsure = ref(false)
	const agreeToPicture = ref(false);
	const columnsList = ref([])
	const isMechanism = ref(false)
	const signFrom = ref<any>({
		openId: "",
		eventId: "",
		height: 1,
		weight: 1,
		eventName: '2024四川“选星计划”篮球项目U系列锦标赛',
		gameGroupId: '',
		gameTeamId: '',
		competeName: '',
		sex: '',
		age: '',
		idCard: '',
		phone: '',
		emContact: '',
		emPhone: '',
		uniformNumber: 0,
		clothingSize: 1,
		regType: '',
		photo: [],
		regFee: 0,
		insuranceFee: 0,
		level: "",
		levelStr: "",
	})
	const signFromRule = {
		eventId: {message: "请选择赛事级别"},
		competeName: { message: '请输入姓名' },
		sex: { message: '请选择性别' },
		idCard: { message: '请输入身份证信息', patternType: 'idCard' },
		height: { message: '请输入身高' },
		weight: { message: '请输入体重' },
		age: { message: '请输入年龄' },
		gameTeamId: { message: '请选择球队' },
		gameGroupId: { message: '请选择报名组别' },
		clothingSize: { message: '请选择衣服尺码' },
		uniformNumber: { message: '请输入球衣号码' },
		regType: { message: '请选择报名类型' },
		photo: { message: '请输入上传蓝底证件照' },
		phone: { message: '请输入联系方式', patternType: 'phone' },
		emContact: { message: '请输入紧急人' },
		emPhone: { message: '请输入紧急联系方式', patternType: 'phone' },
	}
	const signFromRule1 = {
		eventId: {message: "请选择赛事级别"},
		competeName: { message: '请输入姓名' },
		sex: { message: '请选择性别' },
		idCard: { message: '请输入身份证信息', patternType: 'idCard' },
		age: { message: '请输入年龄' },
		gameTeamId: { message: '请选择球队' },
		gameGroupId: { message: '请选择报名组别' },
		regType: { message: '请选择报名类型' },
		photo: { message: '请输入上传蓝底证件照' },
		phone: { message: '请输入联系方式', patternType: 'phone' },
		emContact: { message: '请输入紧急人' },
		emPhone: { message: '请输入紧急联系方式', patternType: 'phone' },
	}

	const price = ref()
	onLoad((options : any) => {
		// getOrderPrice().then(res => {
		// 	if (res.code == 200) {
		// 		price.value = res.data
		// 		signFrom.value.regFee = res.data.orderAmountStr;
		// 		signFrom.value.insuranceFee = res.data.insuranceAmountStr;
		// 	}
		// })

	})

	const agreeChange = (e : any) => {
		agreeToExplain.value = !agreeToExplain.value
	}
	const agreeChange1 = (e : any) => {
		agreeToInsure.value = !agreeToInsure.value
	}
	const agreeChange2 = (e : any) => {
		agreeToPicture.value = !agreeToPicture.value
	}
	const formDataInfo = ref({})
	const personalClick = async () => {
		formDataInfo.value = JSON.parse(JSON.stringify(signFrom.value))
		formDataInfo.value.openId = store.state.user.openId;
		formDataInfo.value.age = Number(signFrom.value.age)
		formDataInfo.value.uniformNumber = Number(signFrom.value.uniformNumber)
		formDataInfo.value.photo = signFrom.value.photo.length == 0 ? '' : signFrom.value.photo[0]?.fullUrl
		let rules : any = signFromRule;

		if (signFrom.value.regType != "SPORTS_MAN") {
			rules = signFromRule1;
		}
		await formValidate(signFrom.value, rules)

		if (formDataInfo.value.phone && !phoneCode(formDataInfo.value.phone)) {
			msg('请输入正确的联系电话', false)
			return false
		}
		if (formDataInfo.value.emPhone && !phoneCode(formDataInfo.value.emPhone)) {
			msg('请输入正确的紧急联系方式', false)
			return false
		}

		submitRequest(formDataInfo.value)
	}
	const submitRequest = (data : any) => {
		signup(data).then(res => {
			if (res.code == 200) {
				orderCreat(res.data)
			} else if (res.code == 201) {
				msg('球衣号重复，请重新填写！')
			}
		})
	}

	const orderCreat = (id : any) => {
		const params = {
			reportId: id,
			openid: uni.getStorageSync('openId'),
			type: "MIN",
			insuranceAmountStr: signFrom.value?.insuranceFee,
			orderAmountStr: signFrom.value?.regFee,
			payType: 1,
			orderRemark: "",
			productType: "GAME"
		}
		creatOrder(params).then(res => {
			if (res.code == 200) {
				if (signFrom.value.regType == "SPORTS_MAN") {
					// 起调支付
					wechatPayment(res.data.payJSON).then((_res : any) => {
						// 支付后检查是否支付
						msg('支付成功')
						const time = setTimeout(() => {
							uni.redirectTo({ url: `/pageSignUp/orderMatchSign/orderMatchSign` })
						}, 500)
					}).catch((err : any) => {
						msg('支付失败，请重试', false)
						setTimeout(() => {
							uni.redirectTo({
								url: "/pageSignUp/orderMatchSign/orderMatchSign"
							})
						})
					})
				} else {
					msg('报名成功');
					uni.redirectTo({ url: `/pageSignUp/orderMatchSign/orderMatchSign` })
				}

			}
		})
	}



	const informationChange = (e : any) => {
		if (e.type == 'cityId') {
			confirmCounty.value = `${e.idList[0].text}/${e.idList[1].text}/${e.idList[2].text}`
			if (e.idList[0]) {
				signFrom.value.provinceCode = e.idList[0].value
				signFrom.value.provinceName = e.idList[0].text
			}
			if (e.idList[1]) {
				signFrom.value.cityCode = e.idList[1].value
				signFrom.value.cityName = e.idList[1].text
			}
			if (e.idList[2]) {
				signFrom.value.districtCode = e.idList[2].value
				signFrom.value.districtName = e.idList[2].text
			}
		} else if (e.type == 'teamName1' && signFrom.value.teamName1) {
			signFrom.value.teamName = ''
		} else if (e.type == 'insCode') {
			signFrom.value.insCode = e.value
			signFrom.value.insName = e.text
		}
	}

	const getAge = (str : string) => {
		if (!str) {
			return str
		}
		const toStr = str.toString()
		const yearStr = toStr.substring(6, 10)
		const dateStr = `${toStr.substring(10, 12)}-${toStr.substring(12, 14)}`
		const birthday = `${yearStr}-${dateStr}`
		const birth = new Date(birthday)
		const today = new Date()
		let age = today.getFullYear() - birth.getFullYear()
		if (
			today.getMonth() < birth.getMonth() ||
			(today.getMonth() == birth.getMonth() && today.getDate() < birth.getDate())
		) {
			age--
		}
		return age
	}

	// 查看报名须知
	const registrationNotice = () => {
		const date = new Date()
		uni.downloadFile({
			url: `https://pro.star.ihehang.com/mini/static/icons/bmtz.pdf?time=${date.getTime()}`,
			success: res => {
				uni.openDocument({
					filePath: res.tempFilePath
				})
			}
		})

	}
	// 查看保险理赔
	const registrationInsure = () => {
		const date = new Date()
		uni.downloadFile({
			url: `https://pro.star.ihehang.com/mini/static/icons/lp.pdf?time=${date.getTime()}`,
			success: res => {
				uni.openDocument({
					filePath: res.tempFilePath
				})
			}
		})

	}
	// 查看肖像权
	const registrationPicture = () => {
		const date = new Date()
		uni.downloadFile({
			url: `https://pro.star.ihehang.com/mini/static/icons/sq.pdf?time=${date.getTime()}`,
			success: res => {
				uni.openDocument({
					filePath: res.tempFilePath
				})
			}
		})

	}
	const agreeNotice = () => {
		agreeToExplain.value = true
	}

	const changeTwoFun = (e : any, ids : any[]) => {
		if (ids.length >= 2 && !e.active) {
			msg('该项目只能选择两项参加')
			return false
		}
		if (!signFrom.value.idCard) {
			msg('请先填写身份证')
			return false
		} else {
			const age = getAge(signFrom.value.idCard)
			if (age > e.maxAge || age < e.minAge) {
				msg(`您的年龄不符合，${e.title}报名年龄在${e.minAge}岁~${e.maxAge}岁之间`)
				return false
			}
			return true
		}
	}

	const projectChange = (data : any) => {
		getEventsItemTree({ eventId: data }).then(res => {
			if (res.code == 200) {
				columnsList.value = res.data
			} else {
				columnsList.value = []
			}
		}).catch(err => {
			columnsList.value = []
		})
	}
	const confirmFromShow = ref(false)
	const confirmFromTime = ref(5)
	const confirmFromTimer = ref(null)
	const confirmCounty = ref('')
	const setConfirmFromTime = () => {
		confirmFromTime.value = 5
		if (confirmFromTimer.value) {
			clearInterval(confirmFromTimer.value)
			confirmFromTimer.value = null
		}
		confirmFromTimer.value = setInterval(() => {
			confirmFromTime.value--
			if (confirmFromTime.value === 0) {
				clearInterval(confirmFromTimer.value)
				confirmFromTimer.value = null
			}
		}, 1000)
	}

	defineExpose({ agreeNotice })
</script>

<template>
	<view class="sign-up">
		<xx-title title="报名赛事" />

		<information :info="signFrom" :mechanism="isMechanism" @change="informationChange" />

	</view>
	<view class="bottom-fixed" :style="{paddingBottom:`calc(${bottomPadding}px + 44rpx)`}">
		<view class="seizeASeat"></view>
	</view>
	<view class="bottom-btn" :style="{paddingBottom:`calc(${bottomPadding}px + 14rpx)`}">
		<view class="personal-tak-care">
			<view>
				<up-checkbox :checked="agreeToExplain" @change="agreeChange"></up-checkbox>
			</view>
			我已阅读<text @click="registrationNotice">《报名须知》</text>
		</view>
		<view class="personal-tak-care">
			<view>
				<up-checkbox :checked="agreeToInsure" @change="agreeChange1"></up-checkbox>
			</view>
			我已阅读<text @click="registrationInsure">《保险理赔》</text>
		</view>
		<view class="personal-tak-care">
			<view>
				<up-checkbox :checked="agreeToPicture" @change="agreeChange2"></up-checkbox>
			</view>
			我已同意<text @click="registrationPicture">《肖像权授权》</text>
		</view>
		<view class="btn">
			<view class="personal-registration" :class="{disabled:!agreeToExplain||!agreeToInsure||!agreeToPicture}"
				@click="personalClick()">提交</view>
		</view>
	</view>
</template>

<style scoped lang="scss">
	::v-deep .uni-selet {
		width: 100% !important;
	}

	::v-deep .uni-select__input-box {
		width: 100% !important;
	}

	::v-deep .uni-select__input-text {
		width: 100% !important;
		white-space: nowrap !important;
		text-overflow: ellipsis !important;
		overflow: hidden !important;

	}

	::v-deep .text-align-left {
		.uni-select {
			.uni-select__selector {
				.uni-select__selector-item {
					text-align: left !important;
				}
			}
		}

	}

	.popup {
		width: calc(100vw - 96rpx);
		height: 75vh;
		display: flex;
		flex-direction: column;

		.popup-head {
			border-bottom: 1px solid #F1F2F4;
			height: 100rpx;
			line-height: 100rpx;
			font-size: 32rpx;
			padding: 0 24rpx;
		}

		.popup-body {
			flex: 1;
			padding: 24rpx 28rpx;
			overflow: hidden;

			.form-body {
				font-size: 28rpx;
				height: 100%;
				overflow: scroll;

				&::-webkit-scrollbar {
					display: none;
				}

				.form-body-item {
					display: flex;
					justify-content: space-between;
					padding: 6rpx 0;

					.label {
						width: 160rpx;
						font-size: 28rpx;
						color: #818496;
						white-space: nowrap;
					}

					.value {
						max-width: calc(100% - 160rpx);
						font-size: 28rpx;
						color: #818496;
						text-align: right;
					}
				}
			}
		}

		.popup-foot {
			border-top: 1px solid #F1F2F4;
			display: flex;
			gap: 20rpx;
			padding: 20rpx 28rpx;
		}
	}

	.sign-up {
		width: 100%;
		min-height: 100vh;
		padding-top: 1rpx;
		background-color: #F5F5F5;

		.notice-content {
			width: 100%;
			white-space: pre-wrap;
			font-size: 28rpx;
			line-height: 1.8;
			color: #9d9d9d;
			padding: 0rpx 60rpx 40rpx;
		}
	}

	.bottom-fixed {
		padding-top: 14px;

		.seizeASeat {
			height: 192rpx;
		}
	}

	.sign-body {
		margin: 32rpx;
		background-color: #FFFFFF;
		border-radius: 16rpx;
		padding: 0 32rpx;

		.sign-item {
			padding: 24rpx 0;
			display: flex;
			align-items: flex-start;
			border-bottom: 1px solid #F5F5F5;

			&:last-child {
				border-bottom: none;
			}

			.sign-label {
				color: #505363;
				font-size: 28rpx;
				width: 160rpx;

				&.required {
					position: relative;
					padding-left: 20rpx;

					&:before {
						content: '*';
						display: block;
						position: absolute;
						color: #ff3c3c;
						top: 0;
						left: 0;
					}
				}
			}

			.sign-value {
				width: calc(100% - 160rpx);
				font-size: 28rpx;
				color: #21252E;
				font-weight: 500;

				input {
					width: 100%;
					font-weight: 500;
				}

				textarea {
					background-color: #F5F5F5;
					border-radius: 12rpx;
					box-sizing: border-box;
					font-weight: 500;
					width: 100%;
					padding: 10rpx;
					height: 150rpx;
				}
			}
		}
	}

	.bottom-btn {
		position: fixed;
		bottom: 0;
		width: 100%;
		padding-left: 28rpx;
		padding-right: 28rpx;
		box-sizing: border-box;
		border-top: 1px solid #F1F2F4;
		padding-top: 14rpx;
		z-index: 10;
		background-color: #FFFFFF;

		.btn {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.personal-tak-care {
			display: flex;
			align-items: center;
			font-size: 28rpx;
			color: #505363;
			margin-bottom: 10rpx;
			font-family: OPPOSans, OPPOSans;
			font-weight: normal;
			font-size: 28rpx;
			color: #333333;
			line-height: 36rpx;
			text-align: left;
			font-style: normal;

			text {
				color: #0091FF;
			}
		}

		.personal-registration {
			background: #FFD200;
			border-radius: 16rpx;
			width: calc(100% - 20rpx);
			border: 1rpx solid #FFD200;
			padding: 16rpx 0;
			letter-spacing: 2rpx;
			font-weight: 500;
			text-align: center;
			font-family: OPPOSans, OPPOSans;
			font-weight: normal;
			font-size: 28rpx;
			color: #333333;
			font-style: normal;

			&.disabled {
				background-color: #E5E5E5;
				color: #818496;
				border: 1rpx solid #E5E5E5;
			}

			&.hollowedOut {
				border: 1rpx solid #92C75B;
				color: #92C75B;
				background-color: transparent;
			}
		}
	}
</style>